package com.hibase.upms.service;


import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hibase.common.entity.User;
import com.hibase.common.exception.HibaseException;
import com.hibase.common.util.EntityUtil;
import com.hibase.upms.entity.user.MdsUser;
import com.hibase.upms.service.user.MdsUserService;
import com.hiibase.core.security.entity.UserDetail;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 用户登录认证信息查询
 * @author Lierh
 * @date Jun 29, 2019
 */
@Slf4j
@Service("userDetailsService")
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private MdsUserService userService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        log.debug("开始登陆验证，用户名为: {}", username);
        MdsUser user = userService.getOne(new QueryWrapper<MdsUser>().eq("login_name",username));
        if (ObjectUtil.isEmpty(user)) {
            throw new HibaseException("该用户不存在");
        }
        if(!user.getBeActive()){
            throw new HibaseException("该用户已被禁用");
        }
        // 用户权限列表，根据用户拥有的权限标识与如 @PreAuthorize("hasAuthority('sys:menu:view')") 标注的接口对比，决定是否可以调用接口
        UserDetail userDetail = new UserDetail();
        Set<String> dbAuthSet = new HashSet<>();
        // 当前用户所拥有的角色
        List<String> list = userService.selectRoleInfosByUserName(username);
        list.forEach(role -> dbAuthSet.add(role));
        // 当前用户所拥有的资源
        List<String> permissionList = userService.selectPermissionsByUserName(username);
        dbAuthSet.addAll(permissionList);
        userDetail.setRoles(dbAuthSet.stream().collect(Collectors.toList()));
        userDetail.setUser(EntityUtil.transform(user, User.class));
        return userDetail;
    }
}